#include "LogOutput.h"

namespace logging {

LogOutput::LogOutput() 
	: Thread(), _mutex(), _lock() {

	Appender* appender = AppenderFactory::create("test", FILE_APPENDER);
	_appenders[appender->getName()] = appender;
}

LogOutput::~LogOutput() {
	teardown();
}

void LogOutput::teardown() {
	sleep(1);
	while ( !_queue.empty() ) {
		write();
	}
	_mutex.destroy();
	join();
	std::cout << "Teardown" << std::endl;
}


void LogOutput::log(Entry *entry) {
	int i = 0;
	do {
		if ( _mutex.lock() ) {
			_queue.push(entry);
			_mutex.unlock();
			return;
		}
		i++;
	} while ( i <= 5 );
	delete entry;
}

void LogOutput::run() {
	while ( 1 ) {
		if ( !_queue.empty() ) {
			write();
		} else {
			usleep(250000);
		}
	}
}

void LogOutput::write() {
	if ( _mutex.lock() ) {
		Entry *entry = _queue.front();
		_queue.pop();

		AppenderMap::const_iterator it = _appenders.begin();
		while ( it != _appenders.end() ) {
			((*it).second)->write(entry);
			it++;
		}

		/*
		std::cout << "LM" << entry->getTimestamp() << " "
			  << entry->getNamespace() << " "
			  << entry->getLevel() << " "
			  << entry->getMessage() << std::endl;
		*/
		delete entry;

		_mutex.unlock();
	}
}

}
